import {getNodeAll} from "@/api/setting";
import constant from "@/utils/constant";

// 缓存用KEY集合
const STORAGE_KEY = {
  ROUTEID_AND_NAME: 'routeid_and_name', // 所有任务节点代码及其名称
};
// 根据key获取本地缓存
const getLocalStorageByItem = (key) => {
  if (!(typeof key === 'string' && key.length > 0)) {
    return null;
  }
  const item = window.localStorage.getItem(key);
  if (item && item.length > 0) {
    return JSON.parse(item);
  }
  return null;
}
// 根据key将对象载入本地缓存中
const setLocalStorageByItem = (key, o) => {
  if (!(typeof key === 'string' && key.length > 0)) {
    return false;
  }
  window.localStorage.setItem(key, JSON.stringify(o));
  return true;
};
// 根据key删掉一条缓存数据
const removeLocalStorageByItem = (key) => {
  if (!(typeof key === 'string' && key.length > 0)) {
    return false;
  }
  window.localStorage.removeItem(key);
  return true;
};
// 本地缓存相关
const localStorageUtil = {
  // 获取所有任务节点信息 {"routeid1":"content1","routeid2":"content2"}
  getRouteidAndNameList: function () {
    let routeList = getLocalStorageByItem(STORAGE_KEY.ROUTEID_AND_NAME);
    if (!routeList) {
      getNodeAll().then(res => {
        if (res.resultCode == constant.SUCCESS && res.data) {
          routeList = {};
          res.data.list.forEach(item => {
            routeList[item.routeid] = item.content;
          });
          setLocalStorageByItem(STORAGE_KEY.ROUTEID_AND_NAME, routeList);
        }
      });
    }
    return routeList;
  }
};

export default localStorageUtil;